package com.buct.coder.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.buct.coder.core.assembler.BaseAssembler;
import com.buct.coder.facade.request.PageRequest;
import com.buct.coder.facade.response.ApiResult;
import com.buct.coder.facade.response.vo.StuContestLogVO;
import com.buct.coder.mapper.ContestMapper;
import com.buct.coder.model.Contest;
import com.buct.coder.model.StudentContestLog;
import com.buct.coder.service.IStudentContestLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 学生比赛记录 前端控制器
 * </p>
 *
 * @author xinzi
 * @since 2022-08-17
 */
@RestController
@RequestMapping("/contest-log")
public class StudentContestLogController {

    @Autowired
    private IStudentContestLogService studentContestLogService;
    @Autowired
    private ContestMapper contestMapper;
    private final BaseAssembler BASE_MAPPER = BaseAssembler.MAPPER;

    @PostMapping("/{stuId}/list")
    public ApiResult<Page<StuContestLogVO>> getPage(@PathVariable("stuId") Long stuId, @RequestBody PageRequest pageRequest) {
        Page<StudentContestLog> page = studentContestLogService.page(
                new Page<>(pageRequest.getPage(), pageRequest.getSize()),
                new LambdaQueryWrapper<StudentContestLog>().eq(StudentContestLog::getStuId, stuId)
        );
        List<StudentContestLog> contestLogs = page.getRecords();
        List<Long> contestIds = contestLogs.stream().map(StudentContestLog::getContestId).collect(Collectors.toList());
        Map<Long, Contest> contestMap = contestMapper.selectList(
                new LambdaQueryWrapper<Contest>().in(Contest::getId, contestIds)
        ).stream().collect(Collectors.toMap(Contest::getId, Function.identity()));
        List<StuContestLogVO> records = contestLogs.stream()
                .map(e -> BASE_MAPPER.toContestLogVO(contestMap.get(e.getContestId()), e))
                .collect(Collectors.toList());
        Page<StuContestLogVO> result = new Page<>();
        result.setTotal(page.getTotal());
        result.setCurrent(page.getCurrent());
        result.setPages(page.getPages());
        result.setSize(page.getSize());
        result.setRecords(records);
        return ApiResult.success(result);
    }

}
